/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiruss.efair.persistence;

import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Hiru
 */
public class FileManager {

	private String filePath = "G:\\files\\";
	private int maxFileSize = 5000 * 1024;
	private int maxMemSize = 4 * 1024;
	private File file;
	private int imageCount = 0;
	private boolean datasheetFound = false;

	public boolean isDatasheetFound() {
		return datasheetFound;
	}

	public int getImageCount() {
		return imageCount;
	}

	public void saveFiles(HttpServletRequest req, long addId) {
		imageCount = 0;
		if (!ServletFileUpload.isMultipartContent(req)) {
			return;
		}

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(maxMemSize);
		// Location to save data that is larger than maxMemSize.
		factory.setRepository(new File("G:\\temp"));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		upload.setSizeMax(maxFileSize);

		try {
			// Parse the request to get file items.
			List<FileItem> fileItems = upload.parseRequest(req);

			// Process the uploaded file items
			for (FileItem fi : fileItems) {
				if (!fi.isFormField()) {
					// Get the uploaded file parameters
					String fieldName = fi.getFieldName();
					System.out.println(fieldName);
					String fileName = fi.getName();
					String contentType = fi.getContentType();
//                    boolean isInMemory = fi.isInMemory();
					long sizeInBytes = fi.getSize();
					// Write the file
					if (fieldName.equalsIgnoreCase("datasheet") && contentType.equalsIgnoreCase("application/pdf")) {
						file = new File(filePath
							+ addId + fileName.substring(fileName.lastIndexOf(".")));
						datasheetFound = true;
						fi.write(file);
					} else if (fieldName.equalsIgnoreCase("images") && contentType.startsWith("image/")) {
						file = new File(filePath
							+ addId + "_" + imageCount + fileName.substring(fileName.lastIndexOf(".")));
						imageCount++;
						fi.write(file);
					}
					System.out.println("Uploaded Filename: " + fileName + " "
						+ "with " + fieldName + " " + fileName + " " + contentType + " " + sizeInBytes);
				} else {
					System.out.println(fi.getFieldName() + " " + fi.getString());
				}
			}

		} catch (Exception ex) {
			System.out.println(ex);
		}
	}
}
